package com.kinglone.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.kinglone.util.DateUtils;
import com.kinglone.util.PropertieUtil;

public class UploadFile extends HttpServlet {
	// 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";
  
    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
						
		System.out.println("-------------------");
		PrintWriter writer = response.getWriter();
		
		if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }
		
		// 返回值提示
		String message = "";
		DiskFileItemFactory factory = new DiskFileItemFactory();
		try {
			
			 // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
	        factory.setSizeThreshold(MEMORY_THRESHOLD);
	        // 设置临时存储目录
	        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
	        
	        ServletFileUpload upload = new ServletFileUpload(factory);
	        
	        // 设置最大文件上传值
	        upload.setFileSizeMax(MAX_FILE_SIZE);
	          
	        // 设置最大请求值 (包含文件和表单数据)
	        upload.setSizeMax(MAX_REQUEST_SIZE);
	  
	        // 构造临时路径来存储上传的文件
	        // 这个路径相对当前应用的目录
	        String uploadPath = getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;	        
	          
	        // 如果目录不存在则创建
	        File uploadDir = new File(uploadPath);
	        if (!uploadDir.exists()) {
	            uploadDir.mkdir();
	        }  
	        
			// 使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入
			List<FileItem> list = upload.parseRequest(request);
			for (FileItem item : list) {
				// 如果fileitem中封装的是普通输入项的数据
				if (item.isFormField()) {
					String name = item.getFieldName();
					String value = item.getString("UTF-8");
					System.out.println("普通字段："+name + "=" + value);
				} else {
					// 如果fileitem中封装的是上传文件
					//得到文件名
					String filename = item.getName();
					System.out.println("上传文件名filename=" + filename);
					if (filename == null || filename.trim().equals("")) {
						continue;
					}
					//处理获取到的上传文件的文件名的路径部分，只保留文件名部分
					filename = filename.substring(filename.lastIndexOf("\\") + 1);
					//获取item中的上传文件的输入流
					InputStream in = item.getInputStream();
					//创建缓冲区
					byte buffer[] = new byte[1024];
					String basepath=PropertieUtil.getValue("config.properties", "upload_url");								
					String relativePath="/upload/img/"+DateUtils.format(new Date(), "yyyyMMdd")+"/";
					String holePath=basepath.trim()+relativePath;
					File f=new File(holePath);
					if(!f.exists()){
						f.mkdirs();
					}
					//创建输出流对象，用于将缓冲区的数据读出到保存路径
					FileOutputStream output = new FileOutputStream(holePath+ "\\" + filename);
					//判断输入流中的数据是否已经读完
					int len = 0;
					//循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示输入流中还有数据
					while ((len = in.read(buffer)) > 0) {
					//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
					output.write(buffer, 0, len);
					}
					in.close();
					output.close();
					message = "success";
				}
			}
		} catch (FileUploadException e) {
				message = "failure";
				e.printStackTrace();
		}
			writer.print(message);

		}

}
